import Vue from 'vue'

const state = {
  cartVisible: false, // 购物车弹窗是否显示
  cartList: [], // 购物车列表
  cash: '0', // 收到现金（用于计算找零）
  payWay: 'wechat', // 支付方式
  memberInfo: null, // 会员信息
  cardInfo: null, // 加油卡信息
  couponList: [], // 优惠券列表
  couponVisible: false,
  oilPriceDiscount: 0.00, // 油品每升优惠
  oilDiscountAmount: 0.00, // 油品优惠金额
  oilCouponDiscount: 0.00, // 油品优惠券金额
  goodsDiscountAmount: 0.00, // 非油优惠金额
  goodsCouponDiscount: 0.00, // 非油优惠券金额
  goodsPromotionId: '', // 商品促销活动ID
  discountValid: {} // 判断优惠是否有效
}
const getters = {
  cartVisible: state => state.cartVisible,
  cartList: state => state.cartList,
  cartCash: state => state.cash,
  memberInfo: state => state.memberInfo,
  memberId: state => state.memberInfo ? state.memberInfo.id : '',
  cardInfo: state => state.cardInfo,
  cardUid: state => state.cardInfo ? state.cardInfo.uid : '',
  cardNo: state => state.cardInfo ? state.cardInfo.cardNo : '',
  cardMemberId: state => state.cardInfo ? state.cardInfo.memberId : '',
  numsOfCartList: state => state.cartList.reduce((pre, item) => pre + (item.type === 'oil' ? 1 : parseInt(item.nums)), 0),
  cartCouponList: state => state.couponList,
  couponVisible: state => state.couponVisible,
  selectedCouponList: state => state.couponList.filter(item => item.selected),
  oilCouponDiscount: state => state.oilCouponDiscount,
  goodsCouponDiscount: state => state.goodsCouponDiscount,
  couponDiscountAmount: state => parseFloat(state.oilCouponDiscount) + parseFloat(state.goodsCouponDiscount),
  // 油品价格优惠力度
  oilPriceDiscount: state => state.oilPriceDiscount,
  cartOilList: state => state.cartList.filter(item => item.type === 'oil'),
  cartGoodsList: state => state.cartList.filter(item => item.type === 'goods'),
  goodsPromotionId: state => state.goodsPromotionId,
  // 油品实付金额
  oilPayAmount: (state, getters) => {
    // 实际支付 = 油机金额 - 油品合计优惠
    if (getters.cartOilList.length > 0) {
      var oil = getters.cartOilList[0]
      return Number((oil.amount - state.oilDiscountAmount).toFixed(2))
    } else {
      return 0.00
    }
  },
  // 油品会员优惠 = 油品合计优惠 - 油品券优惠
  oilMemberDiscount: (state) => {
    return state.oilDiscountAmount - state.oilCouponDiscount
  },
  // 系统优惠 = 油品会员优惠 + 非油优惠
  systemDiscount: (state, getters) => {
    return getters.oilMemberDiscount + state.goodsDiscountAmount
  },
  // 实付金额 = 应付金额 - 优惠金额 - 非油券优惠
  goodsPayAmount: (state, getters) => {
    return getters.cartGoodsAmount - state.goodsDiscountAmount - state.goodsCouponDiscount
  },
  // 购物车总应付金额
  amountOfCartList: state => state.cartList.reduce((pre, item) => pre + parseFloat(item.amount), 0.00),
  // 购物车总实付金额
  cartPayAmount: (state, getters) => {
    return getters.oilPayAmount + getters.goodsPayAmount
  },
  // 购物车油品金额-只能支付一笔油品
  cartOilAmount: (state, getters) => {
    return getters.cartOilList.length > 0 ? getters.cartOilList[0].amount : 0.00
  },
  // 非油商品-应付金额
  cartGoodsAmount: (state, getters) => {
    return getters.cartGoodsList.reduce((pre, item) => pre + parseFloat(item.amount), 0.00)
  },
  // 优惠校验是否通过
  discountValid: state => state.discountValid
}
const mutations = {
  SET_CARTVISIBLE (state, payload) {
    state.cartVisible = payload
  },
  SET_CARTLIST (state, payload) {
    state.cartList = payload
  },
  CLEAR_CARTLIST (state) {
    state.cartList = []
  },
  CLEAR_DISCOUNT_VALID (state) {
    state.discountValid = {}
  },
  ADD_TO_CARTLIST (state, payload) {
    // 判断是油品还是非油，油品不允许重复添加，非油重复添加则需要在数量上加1即可
    if (payload.type === 'oil') {
      if (state.cartList && state.cartList.filter(item => item.id === payload.id).length < 1) {
        state.cartList.push(payload)
      }
    } else if (payload.type === 'goods') {
      var found = false
      for (var i = 0; i < state.cartList.length; i++) {
        if (state.cartList[i].id === payload.id) {
          found = true
          var nums = parseInt(state.cartList[i].nums) + 1
          Vue.set(state.cartList[i], 'nums', nums)
          Vue.set(state.cartList[i], 'amount', ((nums) * state.cartList[i].price).toFixed(2))
          break
        }
      }
      if (!found) {
        payload.nums = 1
        state.cartList.push(payload)
      }
    }
  },
  REMOVE_CART_ITEM (state, payload) {
    for (var i = 0; i < state.cartList.length; i++) {
      if (state.cartList[i].id === payload.id) {
        state.cartList.splice(i, 1)
        break
      }
    }
  },
  SET_CART_ITEM_NUMS (state, payload) {
    for (var i = 0; i < state.cartList.length; i++) {
      if (state.cartList[i].id === payload.id) {
        if (state.cartList[i].type === 'goods') {
          Vue.set(state.cartList[i], 'nums', payload.nums)
          Vue.set(state.cartList[i], 'amount', ((payload.nums) * state.cartList[i].price).toFixed(2))
          break
        } else {
          Vue.message.warning('油品不能修改数量')
        }
      }
    }
  },
  SET_MEMBERINFO (state, payload) {
    state.memberInfo = payload
  },
  // 刷新输入现金的值
  SET_CASH_OPS (state, payload) {
    // 删除
    // 小数点
    // 快捷数字 >= 100的直接替换
    // 00
    // 0-9
    switch (payload) {
      case 'del':
        if (state.cash.length > 0) {
          state.cash = state.cash.substring(0, state.cash.length - 1)
        }
        break
      case 'dot':
        // 先判断是否已有小数点
        if (state.cash && state.cash.indexOf('.') === -1) {
          state.cash = state.cash + '.'
        }
        break
      case '200':
        state.cash = '200'
        break
      case '300':
        state.cash = '300'
        break
      case '400':
        state.cash = '400'
        break
      case '00':
        state.cash = (state.cash * 100) + ''
        break
      default:
        if (state.cash.indexOf('.') > -1) {
          var len = state.cash.split('.')[1]
          if (len.length < 2) {
            state.cash = state.cash + (payload + '')
          }
        } else {
          if (state.cash === '0') {
            state.cash = (payload + '')
          } else {
            state.cash = state.cash + (payload + '')
          }
        }
    }
  },
  SET_CASH (state, payload) {
    state.cash = payload
  },
  SET_COUPON_VISIBLE (state, payload) {
    state.couponVisible = payload
  },
  SET_COUPONLIST (state, payload) {
    state.couponList = payload
  },
  // 设置油品每升优惠
  SET_OIL_PRICE_DISCOUNT (state, payload) {
    state.oilPriceDiscount = payload
  },
  // 设置优惠券选用状态
  SELECT_COUPONS (state, ids) {
    for (var i = 0; i < state.couponList.length; i++) {
      state.couponList[i].selected = false
      for (var j = 0; j < ids.length; j++) {
        if (state.couponList[i].id + '' === ids[j]) {
          state.couponList[i].selected = true
        }
      }
    }
    // 触发Vue数组更新
    state.couponList = [...state.couponList]
  },
  // 设置油品合计优惠
  SET_OIL_DISCOUNT_AMOUNT (state, payload) {
    state.oilDiscountAmount = payload
  },
  // 设置油品券优惠
  SET_OIL_COUPON_DISCOUNT (state, payload) {
    state.oilCouponDiscount = payload
  },
  // 设置加油卡信息
  SET_CARD_INFO (state, payload) {
    state.cardInfo = payload
  },
  // 设置非油优惠金额
  SET_GOODS_DISCOUNT_AMOUNT (state, payload) {
    state.goodsDiscountAmount = payload
  },
  // 设置非油优惠信息
  SET_GOODS_DISCOUNT (state, payload) {
    state.goodsDiscountAmount = parseFloat(payload.goodsDiscountAmount || 0.00)
    state.goodsPromotionId = payload.promotionId || ''
  },
  // 设置非油优惠券优惠
  SET_GOODS_COUPON_DISCOUNT (state, payload) {
    state.goodsCouponDiscount = payload
  },
  SET_DISCOUNT_VALID (state, data) {
    state.discountValid = data
  }
}
// cartItem格式:{id,name,nums,type,price,amount,data(原数据对象)}
const actions = {
  // 显示购物车
  showCartDialog ({commit}) {
    commit('SET_CARTVISIBLE', true)
  },
  // 隐藏购物车
  hideCartDialog ({commit}) {
    commit('CLEAR_CARTLIST')
    commit('SET_CARTVISIBLE', false)
    commit('SET_MEMBERINFO', null)
    commit('SET_CARD_INFO', null)
    commit('SET_COUPONLIST', [])
    commit('SET_CASH', '0')
    commit('SET_OIL_PRICE_DISCOUNT', 0.00)
    commit('SET_OIL_DISCOUNT_AMOUNT', 0.00)
    commit('SET_OIL_COUPON_DISCOUNT', 0.00)
    commit('CLEAR_DISCOUNT_VALID')
  },
  // 添加到购物车
  addToCartList ({commit}, payload) {
    if (payload.commodityId) {
      commit('ADD_TO_CARTLIST', {
        id: payload.commodityId,
        name: payload.commodityName,
        nums: 1,
        type: 'goods',
        price: payload.salePrice,
        amount: (payload.salePrice * 1).toFixed(2),
        data: payload
      })
    } else {
      commit('ADD_TO_CARTLIST', {
        id: payload.id,
        name: payload.gunNo + '号枪 ' + payload.fuelName + ' ' + payload.litre + '升',
        nums: payload.litre,
        type: 'oil',
        price: payload.price,
        amount: payload.amount,
        data: payload
      })
    }
  },
  // 从购物车移除
  removeFromCartList ({commit}, payload) {
    commit('REMOVE_CART_ITEM', payload)
  },
  // 更新商品数量
  setCartItemNums ({commit}, payload) {
    commit('SET_CART_ITEM_NUMS', payload)
  },
  // 清空购物车
  clearCartList ({commit}) {
    commit('CLEAR_CARTLIST')
    commit('SET_MEMBERINFO', null)
    commit('SET_CARD_INFO', null)
    commit('SET_COUPONLIST', [])
    commit('SET_CASH', '0')
    commit('SET_OIL_PRICE_DISCOUNT', 0.00)
    commit('SET_OIL_DISCOUNT_AMOUNT', 0.00)
    commit('SET_OIL_COUPON_DISCOUNT', 0.00)
    commit('SET_GOODS_DISCOUNT_AMOUNT', 0.00)
  },
  // 设置购物车会员信息
  setMemberInfo ({commit}, payload) {
    commit('SET_MEMBERINFO', payload)
    if (!payload) {
      commit('SET_OIL_PRICE_DISCOUNT', 0.00)
      commit('SET_OIL_DISCOUNT_AMOUNT', 0.00)
      commit('SET_OIL_COUPON_DISCOUNT', 0.00)
      commit('SET_COUPONLIST', [])
    }
  },
  setCashOperation ({commit}, payload) {
    commit('SET_CASH_OPS', payload)
  },
  // 显示优惠券选择界面
  showCouponDialog ({commit}) {
    commit('SET_COUPON_VISIBLE', true)
  },
  // 隐藏优惠券选择界面
  hideCouponDialog ({commit}) {
    commit('SET_COUPON_VISIBLE', false)
  },
  // 设置券列表
  setCouponList ({commit}, payload) {
    commit('SET_COUPONLIST', payload)
  },
  // 更新选用优惠券
  updateCouponSelect ({commit}, payload) {
    commit('SELECT_COUPONS', payload.selectedIds ? payload.selectedIds.split(',') || [] : [])
    commit('SET_OIL_PRICE_DISCOUNT', payload.priceDiscount || 0.00)
    commit('SET_OIL_DISCOUNT_AMOUNT', (payload.discountAmount || 0.00) - (payload.goodsCouponAmount || 0.00))
    commit('SET_OIL_COUPON_DISCOUNT', (payload.couponAmount || 0.00) - (payload.goodsCouponAmount || 0.00))
    commit('SET_GOODS_COUPON_DISCOUNT', payload.goodsCouponAmount || 0.00)
    commit('SET_DISCOUNT_VALID', {
      id: payload.memberId ? payload.memberId : payload.cardUid,
      valid: !isNaN(payload.discountAmount) && parseFloat(payload.discountAmount) >= 0
    })
  },
  // 设置油品优惠金额(非会员手动设置优惠时使用)
  setOilDiscountAmount ({commit}, payload) {
    commit('SET_MEMBERINFO', null)
    commit('SET_COUPONLIST', [])
    commit('SET_OIL_DISCOUNT_AMOUNT', payload)
  },
  // 设置购物车列表
  setCartList ({commit}, payload) {
    commit('SET_CARTLIST', payload)
  },
  // 设置购物车加油卡信息
  setCardInfo ({commit}, payload) {
    commit('SET_CARD_INFO', payload)
  },
  setGoodsDiscountAmount ({commit}, payload) {
    commit('SET_GOODS_DISCOUNT', payload)
  },
  // 清除优惠校验信息
  clearDiscountValid ({commit}) {
    commit('CLEAR_DISCOUNT_VALID')
  }
}

export default {
  state,
  getters,
  mutations,
  actions
}
